package com.example.service;

import com.example.entity.DocumentFolder;
import com.example.mapper.DocumentFolderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DocumentFolderService {

    @Autowired
    private DocumentFolderMapper documentFolderMapper;

    /**
     * 创建新文件夹
     */
    @Transactional
    public DocumentFolder createFolder(String folderName, Integer spaceId, Integer parentFolderId,
            String creatorUsername) {
        // 检查文件夹名称是否重复
        int count = documentFolderMapper.checkFolderNameExists(folderName, spaceId, parentFolderId);
        if (count > 0) {
            throw new RuntimeException("文件夹名称已存在");
        }

        DocumentFolder folder = new DocumentFolder();
        folder.setFolderName(folderName);
        folder.setSpaceId(spaceId);
        folder.setParentFolderId(parentFolderId);
        folder.setCreatorUsername(creatorUsername);
        folder.setCreatedAt(LocalDateTime.now());
        folder.setIsDeleted(false);

        documentFolderMapper.insertFolder(folder);
        return folder;
    }

    /**
     * 根据文件夹ID获取文件夹详情
     */
    public DocumentFolder getFolderById(Integer folderId) {
        return documentFolderMapper.getFolderById(folderId);
    }

    /**
     * 根据空间ID获取根目录文件夹列表
     */
    public List<DocumentFolder> getRootFoldersBySpaceId(Integer spaceId) {
        return documentFolderMapper.getRootFoldersBySpaceId(spaceId);
    }

    /**
     * 根据空间ID获取所有文件夹列表
     */
    public List<DocumentFolder> getFoldersBySpaceId(Integer spaceId) {
        return documentFolderMapper.getFoldersBySpaceId(spaceId);
    }

    /**
     * 根据父文件夹ID获取子文件夹列表
     */
    public List<DocumentFolder> getSubFoldersByParentId(Integer parentFolderId) {
        return documentFolderMapper.getSubFoldersByParentId(parentFolderId);
    }

    /**
     * 更新文件夹名称
     */
    @Transactional
    public void updateFolderName(Integer folderId, String newFolderName, String username) {
        DocumentFolder folder = documentFolderMapper.getFolderById(folderId);
        if (folder == null) {
            throw new RuntimeException("文件夹不存在");
        }

        // 检查权限（只有创建者可以修改）
        if (!folder.getCreatorUsername().equals(username)) {
            throw new RuntimeException("没有权限修改该文件夹");
        }

        // 检查新名称是否重复
        int count = documentFolderMapper.checkFolderNameExists(newFolderName, folder.getSpaceId(),
                folder.getParentFolderId());
        if (count > 0) {
            throw new RuntimeException("文件夹名称已存在");
        }

        folder.setFolderName(newFolderName);
        documentFolderMapper.updateFolder(folder);
    }

    /**
     * 删除文件夹
     */
    @Transactional
    public void deleteFolder(Integer folderId, String username) {
        DocumentFolder folder = documentFolderMapper.getFolderById(folderId);
        if (folder == null) {
            throw new RuntimeException("文件夹不存在");
        }

        // 检查权限（只有创建者可以删除）
        if (!folder.getCreatorUsername().equals(username)) {
            throw new RuntimeException("没有权限删除该文件夹");
        }

        // 检查是否有子文件夹
        List<DocumentFolder> subFolders = documentFolderMapper.getSubFoldersByParentId(folderId);
        if (!subFolders.isEmpty()) {
            throw new RuntimeException("文件夹不为空，无法删除");
        }

        // TODO: 检查是否有文档在该文件夹中
        // 这里需要调用DocumentService检查

        documentFolderMapper.deleteFolder(folderId);
    }

    /**
     * 获取文件夹的完整路径
     */
    public List<DocumentFolder> getFolderPath(Integer folderId) {
        return documentFolderMapper.getFolderPath(folderId);
    }

    /**
     * 根据空间ID和创建者获取文件夹列表
     */
    public List<DocumentFolder> getFoldersBySpaceAndCreator(Integer spaceId, String creatorUsername) {
        return documentFolderMapper.getFoldersBySpaceAndCreator(spaceId, creatorUsername);
    }

    /**
     * 构建文件夹树结构
     */
    public List<DocumentFolder> buildFolderTree(Integer spaceId) {
        // 获取根文件夹
        List<DocumentFolder> rootFolders = getRootFoldersBySpaceId(spaceId);

        // 递归构建子文件夹
        for (DocumentFolder folder : rootFolders) {
            buildSubFolderTree(folder);
        }

        return rootFolders;
    }

    /**
     * 递归构建子文件夹树
     */
    private void buildSubFolderTree(DocumentFolder parentFolder) {
        List<DocumentFolder> subFolders = getSubFoldersByParentId(parentFolder.getFolderId());
        
        // 设置子文件夹到children字段
        if (!subFolders.isEmpty()) {
            parentFolder.setChildren(subFolders);
            
            // 递归构建每个子文件夹的子文件夹
            for (DocumentFolder subFolder : subFolders) {
                buildSubFolderTree(subFolder);
            }
        }
    }
}